import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  ProductOutStockOrderGetAllByPagedAndSort,
  ProductShipmentOrdersCreate,
  ProductShipmentOrdersGetInfoByPurchaseOrderId,
  ProductOutStockOrderUpdateOutStcokStatus,
  GetInfoByPurchaseOrderId,
  ProductOutStockGetInboundNumber
} from "@/api/stu/SupplyChainFinance";
import { addres } from "@/utils/public/addres"
import { FXQ } from "@/utils/public/FXQ"
import { emitter } from "@/utils/mitt";
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted, computed } from "vue";
import qs from "qs";
export function useSupplierMaterial() {
  const route = useRoute();
  const Vdialog = ref(false);
  const loading = ref(false);
  const dataList = ref([]);
  const selectId = ref()
  const showType = ref(false)
  const deliveryType = ref(false)
  const isSeal1 = ref(false)
  const isSeal2 = ref(false)
  const isSeal3 = ref(false)
  const isSeal4 = ref(false)
  const nextStep = ref(false)
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns = [
    {
      label: "序号",
      type: "index",
      minWidth: 50
    }, {
      label: "采购方（电商企业）",
      prop: "purchaserInformation",
    }, {
      label: "商品信息",
      prop: "information",
      midthWidth: 400,
    },
    {
      label: "金额（元）",
      prop: "totalMoney",
    }, {
      label: "状态",
      prop: "status",
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.status == "0" ? "warning" : 'success'}>
          {
            row.status == "0" ? "待出库" : "已出库"
          }
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    },
  ];
  const outBoundForm = reactive({
    shipDate: '',
    infoList: '',
    outboundNumber: '',
    totalMoney: 0
  });

  const DispatchForm = reactive({
    trackingNumber: '',
    shipDate: '',
    adress: '',
    purchaseName: "",
    receiveName: "",
    deliverName: "",
    carrierName: "****物流公司",
    orderDate: "",
    deliveryTime: "",
    infoList: '',
    originInfoList: '',
    id: '',
    totalMoney: 0,
    totalAmountInWords: ''
  });


  function handleSizeChange() {
    getList()
  }
  function handleCurrentChange() {
    getList()
  }
  async function getList() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      SEIId: sessionStorage.getItem("seiId"),
    }
    const res = await ProductOutStockOrderGetAllByPagedAndSort(data);
    if (res.success) {
      res.data.items.forEach(item => {
        let total = 0
        let arr = JSON.parse(item.outGoodsInformation)
        item.infoList = arr
        //处理列表展示商品信息
        const result = arr
          .filter(item => item.Quantity !== 0)
          .map(item => `${item.ProductName} ${item.Quantity}`);
        item.information = result.join(', ');
        arr.forEach(a => {
          total += a.Price * a.Quantity
          a.total = a.Price * a.Quantity
        })
        item.totalMoney = total
      })
      dataList.value = res.data.items;
      pagination.total = res.data.totalCount
    } else {
      ElMessage.error(res.msg)
    }
  }

  async function finish() {
    if (!isSeal1.value) {
      ElMessage.warning('领用部门未盖章')
      return
    }
    if (!isSeal2.value) {
      ElMessage.warning('领用人未盖章')
      return
    }
    if (!isSeal3.value) {
      ElMessage.warning('负责人未盖章')
      return
    }
    if (!isSeal4.value) {
      ElMessage.warning('仓库员未盖章')
      return
    }
    const data = qs.stringify({
      id: selectId.value,
      status: 1,
      sEId: sessionStorage.getItem("seiId"),
      outboundNumber: outBoundForm.outboundNumber
    })
    const res = await ProductOutStockOrderUpdateOutStcokStatus(data);
    if (res.success) {
      ElMessage.success('出库成功！');
      ClosePanelVisible()
      getList()
    } else {
      ElMessage.error(res.msg);
    }
  }
  function ClosePanelVisible() {
    Vdialog.value = false
    nextStep.value = false
    showType.value = false
    deliveryType.value = false
    isSeal1.value = false
    isSeal2.value = false
    isSeal3.value = false
    isSeal4.value = false
  }
  async function handleOutBound(row) {
    //获取是否入库
    const data1 = qs.stringify({
      id: row.purchaseOrderId
    })
    let res1 = await GetInfoByPurchaseOrderId(data1)
    if (res1.data && res1.data.status == 1) {
      deliveryType.value = true
    } else {
      deliveryType.value = false
    }
    if (row.status == 1) {
      showType.value = true
    }
    selectId.value = row.productOutStockId
    const data = qs.stringify({
      purchaseOrderId: row.purchaseOrderId
    })
    let res = await ProductShipmentOrdersGetInfoByPurchaseOrderId(data)
    if (res.success) {
      DispatchForm.shipDate = res.data.shippedDate.substring(0, 10)
      DispatchForm.trackingNumber = res.data.trackingNumber
      DispatchForm.adress = res.data.deliveryAddress
      DispatchForm.receiveName = res.data.consignee
      DispatchForm.deliverName = res.data.consigner
      DispatchForm.orderDate = res.data.orderDate.substring(0, 10)
      DispatchForm.deliveryTime = res.data.deliveryDate.substring(0, 10)
      DispatchForm.infoList = row.infoList
      DispatchForm.purchaseName = res.data.purchaseOrderId
      DispatchForm.totalMoney = row.totalMoney
      DispatchForm.totalAmountInWords = res.data.totalAmountInWords
      outBoundForm.infoList = row.infoList
      outBoundForm.totalMoney = row.totalMoney
      outBoundForm.shipDate = res.data.shippedDate.substring(0, 10)
      if (row.status == 1) {
        outBoundForm.outboundNumber = row.outboundNumber
      } else {
        const data = qs.stringify({
          taskId: route.query.taskId,
          planId: route.query.planId,
          dateTime: outBoundForm.shipDate
        })
        let res1 = await ProductOutStockGetInboundNumber(data)
        if (res1.success) {
          outBoundForm.outboundNumber = res1.data
        } else {
          ElMessage.error(res1.message)
        }
      }
      Vdialog.value = true
    } else {
      ElMessage.error(res.msg)
    }
  }

  emitter.on("Outbound1", () => {
    isSeal1.value = true
  })
  emitter.on("Outbound2", () => {
    isSeal2.value = true
  })
  emitter.on("Outbound3", () => {
    isSeal3.value = true
  })
  emitter.on("Outbound4", () => {
    isSeal4.value = true
  })
  onMounted(() => {
    getList()
  })

  function clickBack() {
    nextStep.value = false
    isSeal1.value = false
    isSeal2.value = false
    isSeal3.value = false
    isSeal4.value = false
  }
  return {
    Vdialog,
    loading,
    columns,
    dataList,
    outBoundForm,
    DispatchForm,
    nextStep,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    finish,
    ClosePanelVisible,
    handleOutBound,
    showType,
    deliveryType,
    clickBack,
  }

}
